package com.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.http.HttpException;
import com.gateway.config.AuthProperties;
import com.gateway.utils.JwtTool;
import com.hmall.common.exception.UnauthorizedException;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthorGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher=new AntPathMatcher();
    private final WebClient.Builder builder;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否需要校验
        if(isExclude(request.getPath().toString()))
        {
            return chain.filter(exchange);
        }
        //3.获取并解析token
        List<String> authorization = request.getHeaders().get("Authorization");
        String token=null;
        if (authorization!=null &&!authorization.isEmpty())
        {
             token = authorization.get(0);
        }
        Long userID;
        try{
            userID = jwtTool.parseToken(token);
        }
        catch (UnauthorizedException e)
        {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        String userIDString = userID.toString();
        //  4.传递用户信息
        ServerWebExchange serverWebExchange = exchange.mutate()
                .request(builder -> builder.header("user_info", userIDString))
                .build();
        //5.放行
        return chain.filter(serverWebExchange);
    }

    private boolean isExclude(String path) {
        if (authProperties.getExcludePaths()==null)
        {
            return false;
        }
        for (String pattern: authProperties.getExcludePaths())
        {
            if (antPathMatcher.match(pattern,path))
                return true;
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
